<template>
  <div class="crud-form-dialog-demo">
    <div class="demo-header">
      <h1>CrudFormDialog 表单对话框组件演示</h1>
      <p class="demo-description">
        CrudFormDialog 是一个通用的表单对话框组件，支持动态表单字段配置、表单验证、文件上传等功能。
      </p>
    </div>

    <div class="demo-section">
      <h2>基础用法</h2>
      <p>最基本的表单对话框，包含常用的表单字段类型。</p>

      <div class="demo-actions">
        <CrudButton type="add" @click="openBasicDialog">
          打开基础表单
        </CrudButton>
        <CrudButton type="edit" @click="openEditDialog">
          编辑表单（预填数据）
        </CrudButton>
      </div>

      <!-- 基础表单对话框 -->
      <CrudFormDialog v-model:visible="basicDialogVisible" v-model="basicFormData" title="用户信息表单"
        :form-config="basicFormConfig" :loading="submitLoading" @submit="handleBasicSubmit" @cancel="handleCancel" />
    </div>

    <div class="demo-section">
      <h2>高级用法</h2>
      <p>包含更多字段类型和高级功能的表单对话框。</p>

      <div class="demo-actions">
        <CrudButton type="add" @click="openAdvancedDialog">
          打开高级表单
        </CrudButton>
      </div>

      <!-- 高级表单对话框 -->
      <CrudFormDialog v-model:visible="advancedDialogVisible" v-model="advancedFormData" title="产品信息表单" width="800px"
        :form-config="advancedFormConfig" :loading="submitLoading" :show-reset="true" :before-close="true"
        @submit="handleAdvancedSubmit" @cancel="handleCancel" @reset="handleReset" @field-change="handleFieldChange" />
    </div>

    <div class="demo-section">
      <h2>内联表单</h2>
      <p>紧凑的内联表单布局。</p>

      <div class="demo-actions">
        <CrudButton type="add" @click="openInlineDialog">
          打开内联表单
        </CrudButton>
      </div>

      <!-- 内联表单对话框 -->
      <CrudFormDialog v-model:visible="inlineDialogVisible" v-model="inlineFormData" title="快速搜索" width="600px"
        :form-config="inlineFormConfig" :loading="submitLoading" @submit="handleInlineSubmit" @cancel="handleCancel" />
    </div>

    <div class="demo-section">
      <h2>表单数据展示</h2>
      <div class="data-display">
        <h3>当前表单数据：</h3>
        <pre>{{ JSON.stringify(currentFormData, null, 2) }}</pre>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import CrudFormDialog from './index.vue'
import type { FormConfig } from './types'

/**
 * 组件名称定义
 */
defineOptions({
  name: 'CrudFormDialogDemo'
})

// 对话框显示状态
const basicDialogVisible = ref(false)
const advancedDialogVisible = ref(false)
const inlineDialogVisible = ref(false)

// 提交加载状态
const submitLoading = ref(false)

// 当前表单数据（用于展示）
const currentFormData = ref({})

// 基础表单数据
const basicFormData = reactive({
  name: '',
  email: '',
  age: null,
  gender: '',
  description: '',
  isActive: false
})

// 高级表单数据
const advancedFormData = reactive({
  productName: '',
  category: '',
  price: null,
  tags: [],
  publishDate: '',
  publishTime: '',
  status: '',
  priority: 3,
  rating: 0,
  color: '#409EFF',
  logo: '',
  description: ''
})

// 内联表单数据
const inlineFormData = reactive({
  keyword: '',
  category: '',
  status: ''
})

/**
 * 基础表单配置
 */
const basicFormConfig: FormConfig = {
  labelWidth: '100px',
  fields: [
    {
      prop: 'name',
      label: '姓名',
      type: 'input',
      placeholder: '请输入姓名',
      required: true,
      maxlength: 50,
      showWordLimit: true
    },
    {
      prop: 'email',
      label: '邮箱',
      type: 'input',
      placeholder: '请输入邮箱地址',
      required: true
    },
    {
      prop: 'age',
      label: '年龄',
      type: 'number',
      placeholder: '请输入年龄',
      attrs: {
        min: 1,
        max: 120
      }
    },
    {
      prop: 'gender',
      label: '性别',
      type: 'radio',
      required: true,
      options: [
        { label: '男', value: 'male' },
        { label: '女', value: 'female' },
        { label: '其他', value: 'other' }
      ]
    },
    {
      prop: 'description',
      label: '个人简介',
      type: 'textarea',
      placeholder: '请输入个人简介',
      maxlength: 200,
      showWordLimit: true
    },
    {
      prop: 'isActive',
      label: '是否激活',
      type: 'switch'
    }
  ],
  rules: {
    name: [
      { required: true, message: '请输入姓名', trigger: 'blur' },
      { min: 2, max: 50, message: '姓名长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ],
    gender: [
      { required: true, message: '请选择性别', trigger: 'change' }
    ]
  }
}

/**
 * 高级表单配置
 */
const advancedFormConfig: FormConfig = {
  labelWidth: '120px',
  gutter: 20,
  fields: [
    {
      prop: 'productName',
      label: '产品名称',
      type: 'input',
      placeholder: '请输入产品名称',
      required: true,
      col: { span: 12 }
    },
    {
      prop: 'category',
      label: '产品分类',
      type: 'select',
      placeholder: '请选择产品分类',
      required: true,
      col: { span: 12 },
      options: [
        { label: '电子产品', value: 'electronics' },
        { label: '服装鞋帽', value: 'clothing' },
        { label: '家居用品', value: 'home' },
        { label: '图书音像', value: 'books' }
      ]
    },
    {
      prop: 'price',
      label: '产品价格',
      type: 'number',
      placeholder: '请输入产品价格',
      col: { span: 12 },
      attrs: {
        min: 0,
        precision: 2,
        step: 0.01
      }
    },
    {
      prop: 'tags',
      label: '产品标签',
      type: 'checkbox',
      col: { span: 12 },
      options: [
        { label: '热销', value: 'hot' },
        { label: '新品', value: 'new' },
        { label: '推荐', value: 'recommend' },
        { label: '限时', value: 'limited' }
      ]
    },
    {
      prop: 'publishDate',
      label: '发布日期',
      type: 'date',
      placeholder: '请选择发布日期',
      col: { span: 12 }
    },
    {
      prop: 'publishTime',
      label: '发布时间',
      type: 'time',
      placeholder: '请选择发布时间',
      col: { span: 12 }
    },
    {
      prop: 'status',
      label: '产品状态',
      type: 'select',
      placeholder: '请选择产品状态',
      col: { span: 8 },
      options: [
        { label: '草稿', value: 'draft' },
        { label: '已发布', value: 'published' },
        { label: '已下架', value: 'offline' }
      ]
    },
    {
      prop: 'priority',
      label: '优先级',
      type: 'slider',
      col: { span: 8 },
      attrs: {
        min: 1,
        max: 5,
        'show-tooltip': true
      }
    },
    {
      prop: 'rating',
      label: '产品评分',
      type: 'rate',
      col: { span: 8 },
      attrs: {
        'allow-half': true,
        'show-text': true
      }
    },
    {
      prop: 'color',
      label: '主题色',
      type: 'color-picker',
      col: { span: 12 }
    },
    {
      prop: 'logo',
      label: '产品图片',
      type: 'image-uploader',
      col: { span: 12 },
      uploadConfig: {
        action: '/api/upload/product',
        name: 'file',
        data: { type: 'product-image' },
        allowedTypes: ['image/png', 'image/jpeg', 'image/gif', 'image/webp'],
        maxSize: 5
      }
    },
    {
      prop: 'description',
      label: '产品描述',
      type: 'textarea',
      placeholder: '请输入产品描述',
      maxlength: 500,
      showWordLimit: true,
      col: { span: 24 }
    }
  ],
  rules: {
    productName: [
      { required: true, message: '请输入产品名称', trigger: 'blur' }
    ],
    category: [
      { required: true, message: '请选择产品分类', trigger: 'change' }
    ]
  }
}

/**
 * 内联表单配置
 */
const inlineFormConfig: FormConfig = {
  inline: true,
  labelWidth: '80px',
  fields: [
    {
      prop: 'keyword',
      label: '关键词',
      type: 'input',
      placeholder: '请输入关键词',
      width: '200px'
    },
    {
      prop: 'category',
      label: '分类',
      type: 'select',
      placeholder: '请选择分类',
      width: '150px',
      options: [
        { label: '全部', value: '' },
        { label: '电子产品', value: 'electronics' },
        { label: '服装鞋帽', value: 'clothing' }
      ]
    },
    {
      prop: 'status',
      label: '状态',
      type: 'select',
      placeholder: '请选择状态',
      width: '120px',
      options: [
        { label: '全部', value: '' },
        { label: '启用', value: 'active' },
        { label: '禁用', value: 'inactive' }
      ]
    }
  ]
}

/**
 * 打开基础对话框
 */
const openBasicDialog = (): void => {
  // 重置表单数据
  Object.assign(basicFormData, {
    name: '',
    email: '',
    age: null,
    gender: '',
    description: '',
    isActive: false
  })
  basicDialogVisible.value = true
}

/**
 * 打开编辑对话框（预填数据）
 */
const openEditDialog = (): void => {
  // 预填表单数据
  Object.assign(basicFormData, {
    name: '张三',
    email: 'zhangsan@example.com',
    age: 25,
    gender: 'male',
    description: '这是一个测试用户的个人简介。',
    isActive: true
  })
  basicDialogVisible.value = true
}

/**
 * 打开高级对话框
 */
const openAdvancedDialog = (): void => {
  // 重置表单数据
  Object.assign(advancedFormData, {
    productName: '',
    category: '',
    price: null,
    tags: [],
    publishDate: '',
    publishTime: '',
    status: '',
    priority: 3,
    rating: 0,
    color: '#409EFF',
    logo: '',
    description: ''
  })
  advancedDialogVisible.value = true
}

/**
 * 打开内联对话框
 */
const openInlineDialog = (): void => {
  // 重置表单数据
  Object.assign(inlineFormData, {
    keyword: '',
    category: '',
    status: ''
  })
  inlineDialogVisible.value = true
}

/**
 * 处理基础表单提交
 * @param formData - 表单数据
 */
const handleBasicSubmit = async (formData: Record<string, unknown>): Promise<void> => {
  submitLoading.value = true
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1500))

    currentFormData.value = { ...formData }
    ElMessage.success('基础表单提交成功！')
    basicDialogVisible.value = false
  } catch (error) {
    console.error('基础表单提交失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    submitLoading.value = false
  }
}

/**
 * 处理高级表单提交
 * @param formData - 表单数据
 */
const handleAdvancedSubmit = async (formData: Record<string, unknown>): Promise<void> => {
  submitLoading.value = true

  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 2000))

    currentFormData.value = { ...formData }
    ElMessage.success('高级表单提交成功！')
    advancedDialogVisible.value = false
  } catch (error) {
    console.error('高级表单提交失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    submitLoading.value = false
  }
}

/**
 * 处理内联表单提交
 * @param formData - 表单数据
 */
const handleInlineSubmit = async (formData: Record<string, unknown>): Promise<void> => {
  submitLoading.value = true

  try {
    // 模拟搜索请求
    await new Promise(resolve => setTimeout(resolve, 1000))

    currentFormData.value = { ...formData }
    ElMessage.success('搜索完成！')
    inlineDialogVisible.value = false
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请重试')
  } finally {
    submitLoading.value = false
  }
}

/**
 * 处理取消操作
 */
const handleCancel = (): void => {
  ElMessage.info('操作已取消')
}

/**
 * 处理重置操作
 */
const handleReset = (): void => {
  ElMessage.info('表单已重置')
}

/**
 * 处理字段值变化
 * @param prop - 字段名称
 * @param value - 字段值
 */
const handleFieldChange = (prop: string, value: unknown): void => {
  console.log(`字段 ${prop} 的值变化为:`, value)
}
</script>

<style lang="scss" scoped>
.crud-form-dialog-demo {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;

  .demo-header {
    margin-bottom: 40px;
    text-align: center;

    h1 {
      color: #333;
      margin-bottom: 16px;
      font-size: 28px;
      font-weight: 600;
    }

    .demo-description {
      color: #666;
      font-size: 16px;
      line-height: 1.6;
      max-width: 800px;
      margin: 0 auto;
    }
  }

  .demo-section {
    margin-bottom: 40px;
    padding: 24px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    h2 {
      color: #333;
      margin-bottom: 8px;
      font-size: 20px;
      font-weight: 600;
    }

    p {
      color: #666;
      margin-bottom: 20px;
      line-height: 1.6;
    }

    .demo-actions {
      display: flex;
      gap: 12px;
      flex-wrap: wrap;
    }
  }

  .data-display {
    margin-top: 20px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;

    h3 {
      color: #333;
      margin-bottom: 12px;
      font-size: 16px;
      font-weight: 600;
    }

    pre {
      background: #fff;
      padding: 16px;
      border-radius: 4px;
      border: 1px solid #dee2e6;
      font-size: 12px;
      line-height: 1.5;
      color: #495057;
      overflow-x: auto;
      max-height: 300px;
      overflow-y: auto;
    }
  }
}

/**
 * 响应式设计
 */
@media (max-width: 768px) {
  .crud-form-dialog-demo {
    padding: 10px;

    .demo-header {
      margin-bottom: 20px;

      h1 {
        font-size: 24px;
      }

      .demo-description {
        font-size: 14px;
      }
    }

    .demo-section {
      margin-bottom: 20px;
      padding: 16px;

      h2 {
        font-size: 18px;
      }

      .demo-actions {
        gap: 8px;
      }
    }
  }
}
</style>
